package com.woniuxy.orderServer.controller;


import cn.hutool.core.bean.BeanUtil;
import com.alipay.api.domain.OrderInfoDTO;
import com.woniuxy.commons.util.Result;
import com.woniuxy.orderServer.dto.order.OrderInfoCreateDto;
import com.woniuxy.orderServer.dto.order.OrderInfoDto;
import com.woniuxy.orderServer.form.order.OrderCreatForm;
import com.woniuxy.orderServer.param.order.OrderCreatParam;
import com.woniuxy.orderServer.service.OrderInfoService;
import com.woniuxy.orderServer.util.JwtUtil;
import com.woniuxy.orderServer.util.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 杜岷芫
 * @since 2024年03月20日
 */
@RestController
@Api("订单")
@RequestMapping("/orderInfo")
public class OrderInfoController {
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private RedisUtil redisUtil;

    @ApiOperation("新增订单")
    @PostMapping("/createOrder")
    public Result createOrder(@RequestBody OrderCreatForm form) throws Exception {
        OrderCreatParam param = BeanUtil.toBean(form, OrderCreatParam.class);
        OrderInfoCreateDto orderInfoDto  = orderInfoService.createOrder(param);
        return Result.getResult(OrderInfoCreateDto.class).setData(orderInfoDto).setMsg("成功");
    }
    @ApiOperation("支付订单")
    @PostMapping("/payOrder/{orderNum}")
    public Result payOrder(@PathVariable("orderNum") String orderNum) throws Exception{
        String s =orderInfoService.payOrder(orderNum);
        return Result.getResult(String.class).setMsg("成功").setData(s);
    }



    @PostMapping("/notify")
    public String payNotify(HttpServletRequest req) throws Exception{
        HashMap<String, String> params = new HashMap<>();
        //获取支付宝请求的所有参数
        Map<String, String[]> reqParameterMap = req.getParameterMap();
        //通过迭代，获取所有
        for (Iterator<String> iterator = reqParameterMap.keySet().iterator(); iterator.hasNext();){
            String name = iterator.next();
            String[] values = (String[]) reqParameterMap.get(name);//String[],因为value可能不只一个
            String valueStr="";
            for (int i = 0; i < values.length; i++) {
                valueStr=(i==values.length-1)?valueStr+values[i]:valueStr+values[i]+",";
            }
            params.put(name,valueStr);
        }
        orderInfoService.payNotify(params);
        return "SUCCESS";
    }

}

